<template>
  <div class="admin-outing-apply">
    <div class="header">
      <h2>外出申请记录管理</h2>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="老人姓名">
          <el-input v-model="searchForm.elderName" placeholder="请输入老人姓名" clearable />
        </el-form-item>
        <el-form-item label="申请状态">
          <el-select v-model="searchForm.status" placeholder="请选择申请状态" clearable>
            <el-option label="待处理" value="pending" />
            <el-option label="已批准" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker
            v-model="searchForm.applyDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 外出申请列表 -->
    <el-card>
      <el-table :data="outingApplyList" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="elderName" label="老人姓名" width="120" align="center" />
        <el-table-column prop="familyName" label="家属姓名" width="120" align="center" />
        <el-table-column prop="applyReason" label="外出事由" min-width="200" show-overflow-tooltip />
        <el-table-column prop="outingDate" label="外出日期" width="120" align="center" />
        <el-table-column prop="expectedReturnDate" label="预计返回" width="120" align="center" />
        <el-table-column prop="applyTime" label="申请时间" width="180" align="center" />
        <el-table-column prop="status" label="申请状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="approverName" label="审批人" width="120" align="center" />
        <el-table-column prop="approveTime" label="审批时间" width="180" align="center" />
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              type="success" 
              size="small" 
              @click="handleApprove(row)"
            >
              批准
            </el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              type="danger" 
              size="small" 
              @click="handleReject(row)"
            >
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 查看对话框 -->
    <el-dialog
      title="外出申请详情"
      v-model="viewDialogVisible"
      width="700px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="老人姓名">{{ currentApply.elderName }}</el-descriptions-item>
        <el-descriptions-item label="家属姓名">{{ currentApply.familyName }}</el-descriptions-item>
        <el-descriptions-item label="家属电话">{{ currentApply.familyPhone }}</el-descriptions-item>
        <el-descriptions-item label="负责护工">{{ currentApply.caregiverName }}</el-descriptions-item>
        <el-descriptions-item label="护工电话">{{ currentApply.caregiverPhone }}</el-descriptions-item>
        <el-descriptions-item label="外出事由" :span="2">
          {{ currentApply.applyReason }}
        </el-descriptions-item>
        <el-descriptions-item label="外出日期">{{ currentApply.outingDate }}</el-descriptions-item>
        <el-descriptions-item label="预计返回">{{ currentApply.expectedReturnDate }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ currentApply.applyTime }}</el-descriptions-item>
        <el-descriptions-item label="申请状态">
          <el-tag :type="getStatusTag(currentApply.status)">
            {{ getStatusText(currentApply.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审批人">{{ currentApply.approverName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="审批时间">{{ currentApply.approveTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="审批备注" :span="2">
          {{ currentApply.approveRemark || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="实际返回时间" :span="2">
          {{ currentApply.actualReturnTime || '-' }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog
      :title="`${approveAction === 'approve' ? '批准' : '拒绝'}外出申请`"
      v-model="approveDialogVisible"
      width="500px"
    >
      <el-form :model="approveForm" :rules="approveRules" ref="approveFormRef" label-width="100px">
        <el-form-item label="审批备注" prop="remark">
          <el-input
            v-model="approveForm.remark"
            type="textarea"
            :rows="4"
            :placeholder="`请输入${approveAction === 'approve' ? '批准' : '拒绝'}备注`"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleApproveSubmit" :loading="submitting">
          {{ approveAction === 'approve' ? '批准' : '拒绝' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const loading = ref(false)
const viewDialogVisible = ref(false)
const approveDialogVisible = ref(false)
const submitting = ref(false)
const approveFormRef = ref()

// 搜索表单
const searchForm = reactive({
  elderName: '',
  status: '',
  applyDateRange: []
})

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 外出申请列表
const outingApplyList = ref([])

// 当前申请
const currentApply = ref({})

// 审批相关
const approveAction = ref('approve')
const currentApproveId = ref(null)
const approveForm = reactive({
  remark: ''
})

// 审批表单验证规则
const approveRules = {
  remark: [{ required: true, message: '请输入审批备注', trigger: 'blur' }]
}

// 方法
const getStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    approved: '已批准',
    rejected: '已拒绝',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}

const getStatusTag = (status) => {
  const tagMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
    completed: 'info',
    cancelled: 'info'
  }
  return tagMap[status] || 'info'
}

// 加载外出申请列表
const loadOutingApplies = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    outingApplyList.value = [
      {
        id: 1,
        elderName: '张大爷',
        familyName: '张先生',
        familyPhone: '13800138001',
        caregiverName: '李护工',
        caregiverPhone: '13800138002',
        applyReason: '家庭聚餐，庆祝生日',
        outingDate: '2024-10-05',
        expectedReturnDate: '2024-10-05',
        applyTime: '2024-10-01 14:30:00',
        status: 'pending',
        approverName: '',
        approveTime: '',
        approveRemark: '',
        actualReturnTime: ''
      },
      {
        id: 2,
        elderName: '王大妈',
        familyName: '王女士',
        familyPhone: '13800138003',
        caregiverName: '赵护工',
        caregiverPhone: '13800138004',
        applyReason: '医院复诊检查',
        outingDate: '2024-10-06',
        expectedReturnDate: '2024-10-06',
        applyTime: '2024-10-02 09:15:00',
        status: 'approved',
        approverName: '管理员',
        approveTime: '2024-10-02 10:00:00',
        approveRemark: '同意外出，注意安全',
        actualReturnTime: ''
      },
      {
        id: 3,
        elderName: '李奶奶',
        familyName: '李先生',
        familyPhone: '13800138005',
        caregiverName: '孙护工',
        caregiverPhone: '13800138006',
        applyReason: '外出购物',
        outingDate: '2024-10-07',
        expectedReturnDate: '2024-10-07',
        applyTime: '2024-10-03 16:20:00',
        status: 'rejected',
        approverName: '管理员',
        approveTime: '2024-10-03 17:00:00',
        approveRemark: '天气不佳，建议改期',
        actualReturnTime: ''
      }
    ]
    
    pagination.total = outingApplyList.value.length
  } catch (error) {
    ElMessage.error('加载外出申请列表失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadOutingApplies()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    elderName: '',
    status: '',
    applyDateRange: []
  })
  pagination.current = 1
  loadOutingApplies()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadOutingApplies()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  loadOutingApplies()
}

// 查看申请
const handleView = (row) => {
  currentApply.value = { ...row }
  viewDialogVisible.value = true
}

// 批准申请
const handleApprove = (row) => {
  approveAction.value = 'approve'
  currentApproveId.value = row.id
  approveForm.remark = ''
  approveDialogVisible.value = true
}

// 拒绝申请
const handleReject = (row) => {
  approveAction.value = 'reject'
  currentApproveId.value = row.id
  approveForm.remark = ''
  approveDialogVisible.value = true
}

// 提交审批
const handleApproveSubmit = async () => {
  if (!approveFormRef.value) return
  
  try {
    await approveFormRef.value.validate()
    submitting.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success(`${approveAction.value === 'approve' ? '批准' : '拒绝'}成功`)
    approveDialogVisible.value = false
    loadOutingApplies()
  } catch (error) {
    if (error.errors) {
      ElMessage.error('请完善表单信息')
    } else {
      ElMessage.error('操作失败：' + error.message)
    }
  } finally {
    submitting.value = false
  }
}

// 生命周期
onMounted(() => {
  loadOutingApplies()
})
</script>

<style scoped>
.admin-outing-apply {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
